package com.example.gzysmartcity.ui.fragment.sell;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.PopupMenu;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.gzysmartcity.R;
import com.example.gzysmartcity.databinding.FragmentSellBinding;
import com.example.gzysmartcity.databinding.PopuSell2Binding;
import com.example.gzysmartcity.databinding.PopuSellBinding;
import com.example.gzysmartcity.repository.model.Commodity;
import com.example.gzysmartcity.repository.model.CommodityType;
import com.example.gzysmartcity.repository.model.SellCar;
import com.example.gzysmartcity.ui.adapter.BrAdapter;
import com.example.gzysmartcity.ui.adapter.SellRvAdatper;
import com.example.gzysmartcity.ui.base.BaseFragment;
import com.example.gzysmartcity.utils.PopupUntil;
import com.example.gzysmartcity.viewmodel.SellViewModel;
import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class SellFragment extends BaseFragment<FragmentSellBinding> {
    private List<Commodity.DataBean> commList;
    private PopupMenu menu;
    private boolean search;

    @Override
    protected FragmentSellBinding viewBinding() {
        return FragmentSellBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @SuppressLint({"NonConstantResourceId", "SetTextI18n"})
    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SellViewModel sellViewModel = new ViewModelProvider(this).get(SellViewModel.class);
        b.back.setOnClickListener(v -> remove());
        Banner<Object, BrAdapter> banner = b.getRoot().findViewById(R.id.banner_sell);
        sellViewModel.getCommodityData();
        Handler handler = new Handler();
        sellViewModel.getSellLiveData().observe(getViewLifecycleOwner(), state -> {
            switch (state) {
                case FAIL:
                    ToastUtils.showShort("加载失败");
                    break;
                case SUCCESS:
                    for (CommodityType.DataBean type : sellViewModel.getCommodityTypeList()) {
                        b.tableLayoutSell.addTab(b.tableLayoutSell.newTab().setText(type.getCommodityTypeName()));
                    }
                    //获取当前分类商品
                    commList = new ArrayList<>();
                    sellViewModel.getCommodityRvData(commList, 1);
                    banner.setAdapter(new BrAdapter(sellViewModel.getBrImgList()))
                            .addBannerLifecycleObserver(this)
                            .setLoopTime(2000)
                            .setIndicator(new CircleIndicator(getContext()));
                    //
                    SellRvAdatper adatper = new SellRvAdatper(R.layout.rv_sell);
                    adatper.setNewInstance(commList);
                    b.rvSell.setAdapter(adatper);
                    b.rvSell.setLayoutManager(new LinearLayoutManager(getContext()));
                    //
                    b.tableLayoutSell.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                        @Override
                        public void onTabSelected(TabLayout.Tab tab) {
                            sellViewModel.getCommodityRvData(commList, tab.getPosition() + 1);
                            adatper.notifyDataSetChanged();
                        }

                        @Override
                        public void onTabUnselected(TabLayout.Tab tab) {

                        }

                        @Override
                        public void onTabReselected(TabLayout.Tab tab) {

                        }
                    });
                    b.tableLayoutSell.selectTab(b.tableLayoutSell.getTabAt(0));
                    //
                    b.checkMoney.setOnCheckedChangeListener((buttonView, isChecked) -> {
                        sellViewModel.getCommoditySortMoney(commList, isChecked);
                        adatper.notifyDataSetChanged();
                    });
                    b.checkSellNum.setOnCheckedChangeListener((buttonView, isChecked) -> {
                        sellViewModel.getCommoditySortVolume(commList, isChecked);
                        adatper.notifyDataSetChanged();
                    });
                    b.checkSellDiscount.setOnCheckedChangeListener((buttonView, isChecked) -> {
                        sellViewModel.getCommodityDiscount(commList, isChecked);
                        adatper.notifyDataSetChanged();
                    });
                    //
                    b.searchSell.setSubmitButtonEnabled(true);
                    b.searchSell.setOnCloseListener(() -> {
                        if (search) {
                            sellViewModel.search(commList, "");
                            adatper.notifyDataSetChanged();
                            search = false;
                        }
                        return false;
                    });
                    b.searchSell.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String query) {
                            b.searchSell.setIconified(true);
                            sellViewModel.search(commList, query);
                            adatper.notifyDataSetChanged();
                            search = true;
                            return true;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            return false;
                        }
                    });
                    //
                    adatper.setOnItemClickListener((adapter, view1, position) -> {
                        Commodity.DataBean comm = commList.get(position);
                        PopuSellBinding popuSellBinding = PopuSellBinding.inflate(getLayoutInflater());
                        PopupUntil popupUntil = new PopupUntil();
                        popupUntil.getPopupDataByView(popuSellBinding.getRoot(), requireContext());
                        popuSellBinding.ppsellLiner.setOnClickListener(v -> popupUntil.closePopup());
                        popuSellBinding.tvPpsellMoney.setText("商品价格：" + comm.getMoney());
                        popuSellBinding.tvPpsellName.setText("商品名称：" + comm.getCommodityName());
                        TabLayout.Tab tabAt = b.tableLayoutSell.getTabAt(comm.getCommodityTypeId() - 1);
                        if (tabAt != null)
                            popuSellBinding.tvPpsellType.setText("商品类型：" + tabAt.getText());
                        Glide.with(requireActivity()).load(comm.getPic()).into(popuSellBinding.ppsellImage);
                        popuSellBinding.ppsellAdd.setOnClickListener(v -> {
                            int num = Integer.parseInt(popuSellBinding.tvnum.getText().toString());
                            popuSellBinding.tvnum.setText((num + 1) + "");
                        });
                        popuSellBinding.ppsellRemove.setOnClickListener(v -> {
                            int num = Integer.parseInt(popuSellBinding.tvnum.getText().toString());
                            if (num > 1) {
                                popuSellBinding.tvnum.setText((num - 1) + "");
                            } else {
                                ToastUtils.showShort("最少选择一个");
                            }
                        });
                        popuSellBinding.btnPpsellBuy.setOnClickListener(v -> {
                            PopupUntil until = new PopupUntil();
                            PopuSell2Binding p2 = PopuSell2Binding.inflate(getLayoutInflater());
                            until.getPopupDataByView(p2.getRoot(), requireActivity());
                            p2.p2TvTishi.setText("购买成功");
                            handler.postDelayed(until::closePopup, 1000);
                        });
                        popuSellBinding.btnPpsellAddcar.setOnClickListener(v -> {
                            PopupUntil until = new PopupUntil();
                            PopuSell2Binding p2 = PopuSell2Binding.inflate(getLayoutInflater());
                            until.getPopupDataByView(p2.getRoot(), requireActivity());
                            p2.p2TvTishi.setText("添加购物车成功");
                            handler.postDelayed(() -> {
                                sellViewModel.insertSellCar(new SellCar((long) comm.getId(),comm.getPic(),
                                        comm.getCommodityName(), Integer.parseInt(popuSellBinding.tvnum.getText().toString()), Double.parseDouble(comm.getMoney())));
                                until.closePopup();
                                popupUntil.closePopup();
                            }, 1000);
                        });
                    });
                    break;
            }
        });

        menu = new PopupMenu(getContext(), b.imageSellMenu);
        requireActivity().getMenuInflater().inflate(R.menu.sellmenu, menu.getMenu());
        b.imageSellMenu.setOnClickListener(v -> menu.show());
        menu.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.sell_car:
                    jump(SellCarFragment.class, null, null);
                    break;
                case R.id.custom_list:
                    jump(CustomFragment.class, null, null);
                    break;
                case R.id.expend_sta:
                    jump(ExpendFragment.class, null, null);
                    break;
            }
            return true;
        });
    }

    @Override
    protected String setTitle() {
        return null;
    }

    @Override
    protected boolean showBack() {
        return false;
    }

    @Override
    protected Boolean showBottom() {
        return null;
    }
}
